class_name Checkpoint
extends Node2D


@onready var enemies: Node2D = $Enemies
@onready var playerDeletectionArea: Area2D = $PlayerDeletectionArea


## 启用
@export var enabled: bool = true
## 每次生成的敌人数量
@export var enemy_numbers: int
## 玩家进入检查点后延迟开门的时间
@export var delay_open_door: float = 0.0
## 检查的中含有的门
@export var doors: Array[Door] = []


# 敌人生成数据
var enemy_datas: Array[EnemyData] = []
# 活动的敌人数量
var active_enemy_counter: int = 0
# 已生成的敌人数量
var created_enemy_counter: int = 0
# 生成敌人的总数量
var created_enemy_total: int

# 是否可以开始生成敌人
var is_actived: bool = false
# 是否是最后一个检查点
var is_latest: bool = false



@export var doTest: bool


func _ready():
	if not enabled:
		return

	init_enemy_datas()
	created_enemy_total = enemy_datas.size()

	playerDeletectionArea.body_entered.connect(on_player_enter)

	# TODO test
	if doTest:
		await get_tree().create_timer(2).timeout
		checkpoint_complete()



func _process(_delta: float) -> void:
	if not is_actived:
		return
	if can_create_enemies():
		create_enemies()
	# 完成
	if is_checkpoint_completed():
		checkpoint_complete()


func on_player_enter(body: Node2D):
	var player: Player = body as Player
	if player == null:
		return
	checkpoint_start()
	# 开门
	delay_open_doors()



func delay_open_doors():
	if delay_open_door > 0.0:
		await get_tree().create_timer(delay_open_door).timeout
	for door: Door in doors:
		door.open()


func on_enemy_death(_enemy: Character):
	if not is_actived:
		return
	active_enemy_counter -= 1



func checkpoint_start():
	playerDeletectionArea.set_deferred("monitoring", false)
	StageManager.checkpoint_start.emit()
	is_actived = true
	active_enemy_counter = 0


func checkpoint_complete():
	is_actived = false
	StageManager.checkpoint_complete.emit(self)
	queue_free()


func is_checkpoint_completed():
	# 生成的敌人数量必须要到达生成总数量，若检查点中存在门，则需要判断门中的敌人是否已经生成完毕
	return created_enemy_counter >= created_enemy_total and is_doors_all_enemies_death()




# TODO 生成敌人仍然存在问题


func can_create_enemies() -> bool:
	return is_actived and active_enemy_counter < enemy_numbers and created_enemy_counter < created_enemy_total


func create_enemies():
	var data: Variant = enemy_datas.pop_front()
	if data == null:
		return
	active_enemy_counter += 1
	created_enemy_counter += 1
	StageManager.spawn_enemy_in_checkpoint(data, self)



func init_enemy_datas():
	for placeholder: EnemyPlaceHolder in enemies.get_children():
		var enemy_data = placeholder.enemy_data
		enemy_data.origin_point = placeholder.global_position
		enemy_datas.push_back(enemy_data)
		placeholder.queue_free()


func is_doors_all_enemies_death():
	var done: bool = true
	for door: Door in doors:
		if not door.is_all_enemies_death():
			done = false
			break
	return done
